package frog.lazy.framework.core.wrapper;

import cn.hutool.core.collection.CollUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

/**
 * request.getInputStream 只能读取一次需要把流读取出来存储下次再使用
 */
public class HttpServletWrapper extends HttpServletRequestWrapper {

    private Map<String, String[]> params = new HashMap();

    public HttpServletWrapper(HttpServletRequest request) {
        super(request);
        //将现有parameter传递给params
        this.params.putAll(request.getParameterMap());
    }


    /**
     * 重载构造函数
     * @param request
     * @param extraParams
     */
    public HttpServletWrapper(HttpServletRequest request, Map<String, Object> extraParams) {
        this(request);
        addParameters(extraParams);
    }

    /**
     * 修改此方法主要是因为当RequestMapper中的参数为pojo类型时，
     * 会通过此方法获取所有的请求参数并进行遍历，对pojo属性赋值
     * @return
     */
    @Override
    public Enumeration<String> getParameterNames() {
        ArrayList<String> list = new ArrayList<>();
        for (Map.Entry<String, String[]> entry : params.entrySet()) {
            list.add(entry.getKey());
        }
        return Collections.enumeration(list);
    }

    public void addParameters(Map<String, Object> extraParams) {
        for (Map.Entry<String, Object> entry : extraParams.entrySet()) {
            addParameter(entry.getKey(), entry.getValue());
        }
    }

    /**
     * 重写getParameter，代表参数从当前类中的map获取
     * @param name
     * @return
     */
    @Override
    public String getParameter(String name) {
        String[] values = params.get(name);
        if(values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    /**
     * 同上
     * @param name
     * @return
     */
    @Override
    public String[] getParameterValues(String name) {
        return params.get(name);
    }

    /**
     * 添加参数
     * @param name
     * @param value
     */
    public void addParameter(String name, Object value) {
        if (value != null) {
            if (value instanceof String[]) {
                params.put(name, (String[]) value);
            } else if (value instanceof String) {
                params.put(name, new String[]{(String) value});
            } else {
                params.put(name, new String[]{String.valueOf(value)});
            }
        }
    }

    public Map<String, List<String>> getParams() {
        Map<String, List<String>> paramList = new HashMap<>();
        for (Map.Entry<String, String[]> entry : params.entrySet()) {
            ArrayList<String> list = new ArrayList<>();
            paramList.put(entry.getKey(), CollUtil.newArrayList(entry.getValue()));
        }
        return paramList;
    }
}
